import React, { useEffect, useRef, useState } from 'react';

import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';

import styles from './index.module.scss';
import { useDispatch } from 'react-redux';
import {
  clearHistoryAction,
  historySearchAction,
  clesrSuggestAction,
  searchSuggestAction,
} from '@/store/action/search';
import { useAppSelector } from '@/store';
import { useHistory } from 'react-router-dom';
import classNames from 'classnames';
import Dompurify from 'dompurify'; //防止xss攻击
import { Toast } from 'antd-mobile';
import { removeHistories, setHistories } from '@/utils/storage';

//通过正则设置高亮
function highLiht(keyword: string, item: string) {
  const reg = new RegExp(`(${keyword.trim()})`, 'gi');
  return item.replace(reg, `<span>$1</span>`); //$1表示上面（）里面的内容
}

export default function Search() {
  const [searchKey, setSearchKey] = useState('');
  const dispatch = useDispatch();
  const { historySearch, suggestList } = useAppSelector(
    (state) => state.search
  ); //历史搜索
  const history = useHistory();
  const timeIdRef = useRef(-1);
  //搜索建议
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKey(e.target.value);
    clearTimeout(timeIdRef.current);
    if (!e.target.value.trim()) return dispatch(clesrSuggestAction());
    timeIdRef.current = window.setTimeout(() => {
      dispatch(searchSuggestAction(e.target.value.trim()));
    }, 500);
  };

  useEffect(() => {
    setHistories(historySearch);
  }, [historySearch]);

  useEffect(() => {
    if (!searchKey.trim()) {
      dispatch(clesrSuggestAction());
    }
  }, [dispatch, searchKey]);

  useEffect(() => {
    return () => {
      clearTimeout(timeIdRef.current);
      dispatch(clesrSuggestAction());
    };
  }, [dispatch]);

  //清除历史搜索记录
  const handelClear = () => {
    removeHistories();
    dispatch(clearHistoryAction());
  };
  //返回
  const handleBack = () => {
    dispatch(clesrSuggestAction());
    history.go(-1);
  };
  //点击搜索
  const handleSearch = (key?: string) => {
    if (!searchKey.trim())
      return Toast.show({ content: '搜索不能为空', duration: 1000 });
    if (key) dispatch(historySearchAction(key)); //加入历史搜索
    dispatch(historySearchAction(searchKey));
    history.push('/search/result', { searchKey });
    setSearchKey(''); //清空表单
  };

  //点击搜索建议项/历史项
  const handleClickSuggestAndHistory = (key: string) => {
    dispatch(historySearchAction(key));
    history.push('/search/result', { searchKey: key });
  };

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        onBack={() => handleBack()}
        right={
          <span className="search-text" onClick={() => handleSearch()}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              type="text"
              placeholder="请输入关键字搜索"
              value={searchKey}
              onChange={(e) => handleChange(e)}
              onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            />

            {/* 清空输入框按钮 */}
            {searchKey.trim() && (
              <Icon
                type="iconbtn_tag_close"
                className="icon-close"
                onClick={() => setSearchKey('')}
              />
            )}
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {!!historySearch.length && !searchKey && (
        <div className="history">
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={() => handelClear()}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {historySearch.slice(0, 10).map((item) => (
              <span
                className="history-item"
                key={item}
                onClick={() => handleClickSuggestAndHistory(item)}
              >
                {item}
                <span className="divider"></span>
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 搜素建议结果列表 */}
      <div className={classNames('search-result', 'show')}>
        {!!suggestList.length &&
          suggestList.map((item) => (
            <div className="result-item" key={item}>
              <Icon className="icon-search" type="iconbtn_search" />
              {/* dangerouslySetInnerHTML类似v-html */}
              <div
                className="result-value"
                dangerouslySetInnerHTML={{
                  __html: Dompurify.sanitize(highLiht(searchKey, item)),
                }}
                onClick={() => handleClickSuggestAndHistory(item)}
              >
                {/* {highLiht(searchKey, item)} */}
                {/* <span>{searchKey}</span> */}
                {/* {item} */}
              </div>
            </div>
          ))}
      </div>
    </div>
  );
}
